<template>
  <div class="user-container">
    <table-list
      :columns="columns"
      :data-source="userList"
      :pagination="pagination"
      :search-items="searchItems"
      :actions="actions"
      @tableChange="tableChange"
      @search="handleSearch"
      @reset="resetSearch"
      @action="handleAction"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'roles'">
          <a-space>
            <a-tag v-for="role in record.roles" :key="role.id" color="blue">
              {{ role.name }}
            </a-tag>
          </a-space>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleRoleAssign(record)">分配角色</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除此用户吗？"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelete(record)"
            >
              <a class="danger-text">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
      <template #extraContent>
        <!-- 用户表单弹窗 -->
        <user-form-modal
          v-model:visible="modalVisible"
          :loading="submitLoading"
          :userData="formState"
          @submit="handleFormSubmit"
          @cancel="resetForm"
        />

        <!-- 角色分配弹窗 -->
        <role-assign-modal
          v-model:visible="roleModalVisible"
          :loading="false"
          :submitLoading="roleSubmitLoading"
          :roleList="roleList"
          :userRoles="selectedRoles"
          :userId="currentUserId"
          @submit="handleRoleSubmit"
          @cancel="roleModalVisible = false"
        />
      </template>
    </table-list>
  </div>
</template>

<script setup>
import { getUserList, getRoleList, addUser, updateUser, deleteUser, assignUserRoles } from "@/request/api";
import { UserAddOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import { onMounted, reactive, ref, computed } from "vue";
import TableList from "@/components/TableList.vue";
import { useTableList } from "@/hooks/useTableList";
import UserFormModal from "./components/UserFormModal.vue";
import RoleAssignModal from "./components/RoleAssignModal.vue";

// 角色相关状态
const roleList = ref([]);
const roleModalVisible = ref(false);
const roleSubmitLoading = ref(false);
const selectedRoles = ref([]);
const currentUserId = ref(null);


// 默认表单数据
const defaultForm = {
  id: null,
  username: "",
  password: "",
  name: "",
  email: ""
};

// 表单规则
const rules = {
  username: [{ required: true, message: "请输入用户名" }],
  password: [{ required: (formState) => !formState.id, message: "请输入密码" }],
  name: [{ required: true, message: "请输入姓名" }],
  email: [{ type: "email", message: "请输入正确的邮箱格式" }]
};

// 使用组合式函数
const {
  dataList: userList,
  formState,
  pagination,
  modalVisible,
  submitLoading,
  loadList: loadUserList,
  handleSearch,
  resetSearch,
  tableChange,
  handleAdd,
  handleEdit,
  handleDelete,
  handleFormSubmit,
  resetForm
} = useTableList({
  fetchListApi: getUserList,
  addApi: addUser,
  updateApi: updateUser,
  deleteApi: deleteUser,
  defaultForm,
  formRules: rules,
  defaultQuery: {
    query: ""
  },
  hasPagination: true
});

// 表格列定义
const columns = [
  { title: "用户名", dataIndex: "username", key: "username" },
  { title: "姓名", dataIndex: "name", key: "name" },
  { title: "邮箱", dataIndex: "email", key: "email" },
  { title: "角色", dataIndex: "roles", key: "roles" },
  { title: "创建时间", dataIndex: "created_at", key: "created_at" },
  { title: "操作", key: "action", fixed: "right", width: 250 }
];

// 搜索配置
const searchItems = [
  {
    name: "query",
    label: "关键词",
    component: "a-input",
    props: {
      placeholder: "搜索用户名/姓名/邮箱",
      allowClear: true
    }
  },
  {
    name: 'role',
    label: '角色类型',
    component: 'a-select',
    props: {
      placeholder: "请选择角色类型",
      allowClear: true,
      options: [
        { label: '管理员', value: 'admin' },
        { label: '普通用户', value: 'user' },
      ]
    }
  }
];

// 操作按钮配置
const actions = [
  {
    label: "新增用户",
    props: {
      type: "primary"
    },
    icon: UserAddOutlined,
    handler: handleAdd,
    key: "add",
    permission: "system:user:add"
  }
];

// 处理操作按钮点击
const handleAction = (action) => {
  if (action.key === "add") {
    handleAdd();
  }
};

// 加载角色列表
const loadRoleList = async () => {
  try {
    const res = await getRoleList();
    if (res.code === 200) {
      roleList.value = res.data.list;
    } else {
      message.error(res.message || "获取角色列表失败");
    }
  } catch (error) {
    console.error("加载角色列表出错:", error);
    message.error("加载角色列表失败");
  }
};

// 打开角色分配模态框
const handleRoleAssign = (record) => {
  currentUserId.value = record.id;
  selectedRoles.value = record.roles ? record.roles.map((role) => role.id) : [];
  roleModalVisible.value = true;
};

// 提交角色分配
const handleRoleSubmit = async (data) => {
  roleSubmitLoading.value = true;
  try {
    const res = await assignUserRoles(data);

    if (res.code === 200) {
      message.success("角色分配成功");
      roleModalVisible.value = false;
      await loadUserList();
    } else {
      message.error(res.message || "角色分配失败");
    }
  } catch (error) {
    console.error("分配角色出错:", error);
    message.error("角色分配失败");
  } finally {
    roleSubmitLoading.value = false;
  }
};

onMounted(() => {
  loadRoleList();
});
</script>

<style scoped>
.user-container {
  padding: 20px;
}
.danger-text {
  color: #ff4d4f;
}
.form-help-text {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}
</style>
